package com.imut.lagain.service.impl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.imut.lagain.entity.*;
import com.imut.lagain.repository.*;
import com.imut.lagain.service.IFinalAnswerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.security.SecureRandom;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 最终答案之锁服务实现类
 */
@Service
@Transactional
public class FinalAnswerServiceImpl implements IFinalAnswerService {
    private static final Logger log = LoggerFactory.getLogger(FinalAnswerServiceImpl.class);


    @Autowired
    private FinalAnswerLockRepository lockRepository;

    @Autowired
    private UnlockHistoryRepository historyRepository;

    @Autowired
    private AnswerLockBackupRepository backupRepository;

    @Autowired
    private AnswerLockReminderRepository reminderRepository;

    private final BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
    private final SecureRandom secureRandom = new SecureRandom();

    // 移除重复方法定义，使用接口要求的方法名

    // 移除重复方法定义

    // 移除重复方法定义

    // 移除重复方法定义

    // 移除重复方法定义

    // 移除重复方法定义
    private String generateSalt() {
        byte[] salt = new byte[16];
        secureRandom.nextBytes(salt);
        return Base64.getEncoder().encodeToString(salt);
    }

    // 移除重复的private方法定义

    // 移除不存在于接口中的方法

    // 移除重复方法定义

    // 实现接口要求的方法
    @Override
    public Map<String, Object> createFinalAnswerLock(Long userId, String title, String description, String password, String unlockDate) {
        Map<String, Object> result = new HashMap<>();
        try {
            // 解析unlockDate字符串为LocalDateTime
            LocalDateTime unlockDateTime = LocalDateTime.parse(unlockDate);
            
            Map<String, Object> passwordValidation = validatePasswordStrength(password);
            if (!(Boolean) passwordValidation.get("isValid")) {
                result.put("success", false);
                result.put("message", "密码强度不足：" + passwordValidation.get("message"));
                return result;
            }
            
            String passwordHash = passwordEncoder.encode(password);
            FinalAnswerLock lock = new FinalAnswerLock();
            lock.setUserId(userId);
            lock.setLockName(title);
            lock.setLockDescription(description);
            lock.setPasswordHash(passwordHash);
            lock.setPasswordHint("");
            lock.setUnlockDate(unlockDateTime);
            lock.setContentType("text");
            lock.setStatus("locked");
            lock.setEncryptionLevel(1);
            lock.setPriority(1);
            lock.setCategory("personal");
            lockRepository.insert(lock);
            
            createBackup(lock.getId(), userId, "auto", "Lock created");
            recordUnlockHistory(lock.getId(), userId, "create", "success", null, "Lock created successfully");
            
            result.put("success", true);
            result.put("message", "答案锁创建成功");
            result.put("lockId", lock.getId());
            result.put("lock", convertToMap(lock));
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "创建失败：" + e.getMessage());
        }
        return result;
    }

    @Override
    public Map<String, Object> restoreAnswer(Long answerId, Long userId) {
        Map<String, Object> result = new HashMap<>();
        try {
            Optional<FinalAnswerLock> lockOpt = lockRepository.findByIdAndUserIdAndDeletedAtIsNull(answerId, userId);
            if (!lockOpt.isPresent()) {
                result.put("success", false);
                result.put("message", "答案不存在或无权限");
                return result;
            }
            
            FinalAnswerLock lock = lockOpt.get();
            lock.setDeletedAt(null);
            lock.setUpdatedAt(LocalDateTime.now());
            lockRepository.updateById(lock);
            
            result.put("success", true);
            result.put("message", "答案恢复成功");
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "恢复答案失败：" + e.getMessage());
        }
        return result;
    }

    @Override
    public Map<String, Object> restoreAnswerLock(Long backupId, Long userId) {
        Map<String, Object> result = new HashMap<>();
        try {
            Optional<AnswerLockBackup> backupOpt = backupRepository.findByIdAndUserId(backupId, userId);
            if (!backupOpt.isPresent()) {
                result.put("success", false);
                result.put("message", "备份不存在或无权限");
                return result;
            }
            
            AnswerLockBackup backup = backupOpt.get();
            if (backup.getIsRestored()) {
                result.put("success", false);
                result.put("message", "备份已经被恢复过");
                return result;
            }
            
            backup.setIsRestored(true);
            backup.setRestoredAt(LocalDateTime.now());
            backupRepository.updateById(backup);
            
            result.put("success", true);
            result.put("message", "答案锁恢复成功");
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "恢复答案锁失败：" + e.getMessage());
        }
        return result;
    }

    @Override
    public Map<String, Object> uploadAnswerContent(Long lockId, String contentType, String content, String filePath) {
        Map<String, Object> result = new HashMap<>();
        try {
            FinalAnswerLock lock = lockRepository.selectById(lockId);
            if (lock == null) {
                result.put("success", false);
                result.put("message", "锁不存在");
                return result;
            }
            if (!"locked".equals(lock.getStatus())) {
                result.put("success", false);
                result.put("message", "只能向锁定状态的锁上传内容");
                return result;
            }
            
            if ("text".equals(contentType)) {
                lock.setTextContent(content);
                lock.setContentType("text");
            } else if ("file".equals(contentType)) {
                lock.setFileContent(filePath);
                lock.setContentType("file");
            }
            
            lock.setUpdatedAt(LocalDateTime.now());
            lockRepository.updateById(lock);
            
            result.put("success", true);
            result.put("message", "内容上传成功");
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "上传失败：" + e.getMessage());
        }
        return result;
    }

    @Override
    public Map<String, Object> attemptUnlock(Long lockId, String password, Long userId) {
        Map<String, Object> result = new HashMap<>();
        try {
            Optional<FinalAnswerLock> lockOpt = lockRepository.findByIdAndUserIdAndDeletedAtIsNull(lockId, userId);
            if (!lockOpt.isPresent()) {
                result.put("success", false);
                result.put("message", "锁不存在或无权限");
                return result;
            }
            
            FinalAnswerLock lock = lockOpt.get();
            if (lock.getUnlockDate().isAfter(LocalDateTime.now())) {
                result.put("success", false);
                result.put("message", "尚未到达解锁时间");
                result.put("unlockDate", lock.getUnlockDate());
                return result;
            }
            
            boolean passwordValid = passwordEncoder.matches(password, lock.getPasswordHash());
            if (passwordValid) {
                lock.setStatus("unlocked");
                lock.setUnlockTime(LocalDateTime.now());
                lock.setUnlockAttempts(0);
                lock.setViewCount(lock.getViewCount() + 1);
                lock.setLastViewedAt(LocalDateTime.now());
                lockRepository.updateById(lock);
                
                result.put("success", true);
                result.put("message", "解锁成功");
                result.put("content", getUnlockedContent(lock));
                result.put("unlockTime", lock.getUnlockTime());
            } else {
                lock.setUnlockAttempts(lock.getUnlockAttempts() + 1);
                lockRepository.updateById(lock);
                
                result.put("success", false);
                result.put("message", "密码错误");
                result.put("remainingAttempts", lock.getMaxAttempts() - lock.getUnlockAttempts());
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "解锁失败：" + e.getMessage());
        }
        return result;
    }

    @Override
    public Map<String, Object> performUnlockRitual(Long lockId, Long userId) {
        Map<String, Object> result = new HashMap<>();
        try {
            Optional<FinalAnswerLock> lockOpt = lockRepository.findByIdAndUserIdAndDeletedAtIsNull(lockId, userId);
            if (!lockOpt.isPresent()) {
                result.put("success", false);
                result.put("message", "锁不存在或无权限");
                return result;
            }
            
            FinalAnswerLock lock = lockOpt.get();
            if ("unlocked".equals(lock.getStatus())) {
                result.put("success", false);
                result.put("message", "锁已解锁，无需仪式");
                return result;
            }
            
            // 简单的仪式实现
            lock.setUnlockRitualCompleted(true);
            lock.setRitualType("meditation");
            lock.setUpdatedAt(LocalDateTime.now());
            lockRepository.updateById(lock);
            
            result.put("success", true);
            result.put("message", "解锁仪式完成");
            result.put("ritualType", "meditation");
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "仪式执行失败：" + e.getMessage());
        }
        return result;
    }

    @Override
    public Map<String, Object> getUserAnswerLocks(Long userId, String status) {
        Map<String, Object> result = new HashMap<>();
        try {
            List<FinalAnswerLock> locks;
            if ("all".equals(status)) {
                locks = lockRepository.findByUserIdAndDeletedAtIsNull(userId);
            } else {
                locks = lockRepository.findByUserIdAndStatusAndDeletedAtIsNull(userId, status);
            }
            
            List<Map<String, Object>> lockList = locks.stream()
                .map(this::convertToSummaryMap)
                .collect(Collectors.toList());
            
            result.put("success", true);
            result.put("locks", lockList);
            result.put("total", locks.size());
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "获取锁列表失败：" + e.getMessage());
        }
        return result;
    }

    @Override
    public Map<String, Object> getAnswerLockDetails(Long lockId, Long userId) {
        Map<String, Object> result = new HashMap<>();
        try {
            Optional<FinalAnswerLock> lockOpt = lockRepository.findByIdAndUserIdAndDeletedAtIsNull(lockId, userId);
            if (!lockOpt.isPresent()) {
                result.put("success", false);
                result.put("message", "锁不存在或无权限");
                return result;
            }
            
            FinalAnswerLock lock = lockOpt.get();
            result.put("success", true);
            result.put("lock", convertToMap(lock));
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "获取锁详情失败：" + e.getMessage());
        }
        return result;
    }

    @Override
    public Map<String, Object> updateAnswerLock(Long lockId, Long userId, String title, String description, String unlockDate) {
        Map<String, Object> result = new HashMap<>();
        try {
            Optional<FinalAnswerLock> lockOpt = lockRepository.findByIdAndUserIdAndDeletedAtIsNull(lockId, userId);
            if (!lockOpt.isPresent()) {
                result.put("success", false);
                result.put("message", "锁不存在或无权限");
                return result;
            }
            
            FinalAnswerLock lock = lockOpt.get();
            if (title != null) lock.setLockName(title);
            if (description != null) lock.setLockDescription(description);
            if (unlockDate != null) {
                LocalDateTime unlockDateTime = LocalDateTime.parse(unlockDate);
                lock.setUnlockDate(unlockDateTime);
            }
            lock.setUpdatedAt(LocalDateTime.now());
            lockRepository.updateById(lock);
            
            result.put("success", true);
            result.put("message", "锁更新成功");
            result.put("lock", convertToMap(lock));
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "更新锁失败：" + e.getMessage());
        }
        return result;
    }

    @Override
    public Map<String, Object> deleteAnswerLock(Long lockId, Long userId) {
        Map<String, Object> result = new HashMap<>();
        try {
            Optional<FinalAnswerLock> lockOpt = lockRepository.findByIdAndUserIdAndDeletedAtIsNull(lockId, userId);
            if (!lockOpt.isPresent()) {
                result.put("success", false);
                result.put("message", "锁不存在或无权限");
                return result;
            }
            
            FinalAnswerLock lock = lockOpt.get();
            lock.setDeletedAt(LocalDateTime.now());
            lockRepository.updateById(lock);
            
            result.put("success", true);
            result.put("message", "锁删除成功");
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "删除锁失败：" + e.getMessage());
        }
        return result;
    }

    @Override
    public Map<String, Object> changePassword(Long lockId, Long userId, String oldPassword, String newPassword) {
        Map<String, Object> result = new HashMap<>();
        try {
            Optional<FinalAnswerLock> lockOpt = lockRepository.findByIdAndUserIdAndDeletedAtIsNull(lockId, userId);
            if (!lockOpt.isPresent()) {
                result.put("success", false);
                result.put("message", "锁不存在或无权限");
                return result;
            }
            
            FinalAnswerLock lock = lockOpt.get();
            if (!passwordEncoder.matches(oldPassword, lock.getPasswordHash())) {
                result.put("success", false);
                result.put("message", "原密码错误");
                return result;
            }
            
            Map<String, Object> passwordValidation = validatePasswordStrength(newPassword);
            if (!(Boolean) passwordValidation.get("isValid")) {
                result.put("success", false);
                result.put("message", "新密码强度不足：" + passwordValidation.get("message"));
                return result;
            }
            
            lock.setPasswordHash(passwordEncoder.encode(newPassword));
            lock.setUpdatedAt(LocalDateTime.now());
            lockRepository.updateById(lock);
            
            result.put("success", true);
            result.put("message", "密码修改成功");
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "修改密码失败：" + e.getMessage());
        }
        return result;
    }

    @Override
    public Map<String, Object> getUnlockHistory(Long lockId, Long userId) {
        Map<String, Object> result = new HashMap<>();
        try {
            Optional<FinalAnswerLock> lockOpt = lockRepository.findByIdAndUserIdAndDeletedAtIsNull(lockId, userId);
            if (!lockOpt.isPresent()) {
                result.put("success", false);
                result.put("message", "锁不存在或无权限");
                return result;
            }
            
            List<UnlockHistory> historyList = historyRepository.findByLockIdOrderByCreatedAtDesc(lockId);
            List<Map<String, Object>> history = historyList.stream()
                .map(h -> {
                    Map<String, Object> historyMap = new HashMap<>();
                    historyMap.put("attemptType", h.getAttemptType());
                    historyMap.put("result", h.getAttemptResult());
                    historyMap.put("time", h.getCreatedAt());
                    historyMap.put("ipAddress", h.getIpAddress());
                    return historyMap;
                })
                .collect(Collectors.toList());
            
            result.put("success", true);
            result.put("history", history);
            result.put("totalAttempts", historyList.size());
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "获取解锁历史失败：" + e.getMessage());
        }
        return result;
    }

    @Override
    public Map<String, Object> setUnlockReminder(Long lockId, Long userId, String reminderTime, String reminderMessage) {
        Map<String, Object> result = new HashMap<>();
        try {
            Optional<FinalAnswerLock> lockOpt = lockRepository.findByIdAndUserIdAndDeletedAtIsNull(lockId, userId);
            if (!lockOpt.isPresent()) {
                result.put("success", false);
                result.put("message", "锁不存在或无权限");
                return result;
            }
            
            AnswerLockReminder reminder = new AnswerLockReminder();
            reminder.setLockId(lockId);
            reminder.setUserId(userId);
            reminder.setReminderTime(LocalDateTime.parse(reminderTime));
            reminder.setReminderMessage(reminderMessage);
            reminder.setReminderStatus("active");
            reminderRepository.insert(reminder);
            
            result.put("success", true);
            result.put("message", "提醒设置成功");
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "设置提醒失败：" + e.getMessage());
        }
        return result;
    }

    @Override
    public Map<String, Object> getUpcomingUnlocks(Long userId, Integer days) {
        Map<String, Object> result = new HashMap<>();
        try {
            LocalDateTime endDate = LocalDateTime.now().plusDays(days != null ? days : 7);
            List<FinalAnswerLock> upcomingLocks = lockRepository.findUpcomingUnlocks(
                userId, LocalDateTime.now(), endDate);
            
            List<Map<String, Object>> lockList = upcomingLocks.stream()
                .map(this::convertToSummaryMap)
                .collect(Collectors.toList());
            
            result.put("success", true);
            result.put("upcomingLocks", lockList);
            result.put("total", lockList.size());
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "获取即将解锁列表失败：" + e.getMessage());
        }
        return result;
    }

    @Override
    public Map<String, Object> shareAnswerLock(Long lockId, Long userId, String shareType) {
        Map<String, Object> result = new HashMap<>();
        try {
            Optional<FinalAnswerLock> lockOpt = lockRepository.findByIdAndUserIdAndDeletedAtIsNull(lockId, userId);
            if (!lockOpt.isPresent()) {
                result.put("success", false);
                result.put("message", "锁不存在或无权限");
                return result;
            }
            
            FinalAnswerLock lock = lockOpt.get();
            String shareToken = UUID.randomUUID().toString();
            
            result.put("success", true);
            result.put("message", "分享链接生成成功");
            result.put("shareToken", shareToken);
            result.put("shareType", shareType);
            result.put("lockTitle", lock.getLockName());
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "生成分享链接失败：" + e.getMessage());
        }
        return result;
    }

    @Override
    public Map<String, Object> getAnswerLockStatistics(Long userId) {
        Map<String, Object> result = new HashMap<>();
        try {
            List<FinalAnswerLock> allLocks = lockRepository.findByUserIdAndDeletedAtIsNull(userId);
            
            long totalLocks = allLocks.size();
            long lockedCount = allLocks.stream().filter(lock -> "locked".equals(lock.getStatus())).count();
            long unlockedCount = allLocks.stream().filter(lock -> "unlocked".equals(lock.getStatus())).count();
            
            Map<String, Long> categoryStats = allLocks.stream()
                .collect(Collectors.groupingBy(FinalAnswerLock::getCategory, Collectors.counting()));
            
            result.put("success", true);
            result.put("totalLocks", totalLocks);
            result.put("lockedCount", lockedCount);
            result.put("unlockedCount", unlockedCount);
            result.put("categoryStats", categoryStats);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "获取统计信息失败：" + e.getMessage());
        }
        return result;
    }

    @Override
    public Map<String, Object> validatePasswordStrength(String password) {
        Map<String, Object> result = new HashMap<>();
        
        if (password == null || password.length() < 8) {
            result.put("isValid", false);
            result.put("message", "密码长度至少8位");
            return result;
        }
        
        boolean hasUpper = password.chars().anyMatch(Character::isUpperCase);
        boolean hasLower = password.chars().anyMatch(Character::isLowerCase);
        boolean hasDigit = password.chars().anyMatch(Character::isDigit);
        boolean hasSpecial = password.chars().anyMatch(ch -> "!@#$%^&*()_+-=[]{}|;:,.<>?".indexOf(ch) >= 0);
        
        int score = 0;
        if (hasUpper) score++;
        if (hasLower) score++;
        if (hasDigit) score++;
        if (hasSpecial) score++;
        
        if (score >= 3) {
            result.put("isValid", true);
            result.put("message", "密码强度良好");
            result.put("score", score);
        } else {
            result.put("isValid", false);
            result.put("message", "密码需包含大小写字母、数字和特殊字符中的至少3种");
            result.put("score", score);
        }
        
        return result;
    }
    
    @Override
    public Map<String, Object> generateRandomPassword(Integer length, Boolean includeSpecialChars) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            int pwdLength = length != null ? length : 12;
            boolean includeSpecial = includeSpecialChars != null ? includeSpecialChars : true;
            
            StringBuilder chars = new StringBuilder("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789");
            if (includeSpecial) {
                chars.append("!@#$%^&*()_+-=[]{}|;:,.<>?");
            }
            
            StringBuilder password = new StringBuilder();
            for (int i = 0; i < pwdLength; i++) {
                int index = secureRandom.nextInt(chars.length());
                password.append(chars.charAt(index));
            }
            
            result.put("success", true);
            result.put("password", password.toString());
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "生成密码失败：" + e.getMessage());
        }
        
        return result;
    }
    
    @Override
    public Map<String, Object> backupAnswerLock(Long lockId, Long userId) {
        Map<String, Object> result = new HashMap<>();
        try {
            Optional<FinalAnswerLock> lockOpt = lockRepository.findByIdAndUserIdAndDeletedAtIsNull(lockId, userId);
            if (!lockOpt.isPresent()) {
                result.put("success", false);
                result.put("message", "答案锁不存在或无权限");
                return result;
            }
            
            FinalAnswerLock lock = lockOpt.get();
            AnswerLockBackup backup = new AnswerLockBackup();
            backup.setOriginalAnswerId(lockId);
            backup.setUserId(userId);
            backup.setBackupType("manual");
            backup.setBackupContent(convertLockToJson(lock));
            backup.setBackupReason("手动备份");
            backup.setCreatedAt(LocalDateTime.now());
            
            backupRepository.insert(backup);
            
            result.put("success", true);
            result.put("message", "答案锁备份成功");
            result.put("backupId", backup.getId());
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "备份答案锁失败：" + e.getMessage());
        }
        return result;
    }

    // 恢复被删除但需要的方法
    private void createBackup(Long lockId, Long userId, String backupType, String notes) {
        try {
            FinalAnswerLock lock = lockRepository.selectById(lockId);
            if (lock != null) {
                
                AnswerLockBackup backup = new AnswerLockBackup();
                backup.setOriginalAnswerId(lockId);
                backup.setUserId(userId);
                backup.setBackupType(backupType);
                backup.setBackupContent(convertLockToJson(lock));
                backup.setBackupReason(notes);
                backup.setCreatedAt(LocalDateTime.now());
                
                backupRepository.insert(backup);
            }
        } catch (Exception e) {
            log.error("创建备份失败", e);
        }
    }

    private void recordUnlockHistory(Long lockId, Long userId, String attemptType, String result, String ipAddress, String context) {
        try {
            UnlockHistory history = new UnlockHistory();
            history.setLockId(lockId);
            history.setUserId(userId);
            history.setAttemptType(attemptType);
            history.setAttemptResult(result);
            history.setIpAddress(ipAddress);
            history.setUnlockContext(context);
            
            historyRepository.insert(history);
        } catch (Exception e) {
            log.error("记录解锁历史失败", e);
        }
    }

    private Map<String, Object> getUnlockedContent(FinalAnswerLock lock) {
        Map<String, Object> content = new HashMap<>();
        content.put("title", lock.getLockName());
        content.put("description", lock.getLockDescription());
        content.put("category", lock.getCategory());
        content.put("unlockDate", lock.getUnlockDate());
        content.put("unlockTime", lock.getUnlockTime());
        return content;
    }

    private Map<String, Object> convertToMap(FinalAnswerLock lock) {
        Map<String, Object> map = new HashMap<>();
        map.put("id", lock.getId());
        map.put("lockName", lock.getLockName());
        map.put("lockDescription", lock.getLockDescription());
        map.put("category", lock.getCategory());
        map.put("status", lock.getStatus());
        map.put("unlockDate", lock.getUnlockDate());
        map.put("createdAt", lock.getCreatedAt());
        map.put("viewCount", lock.getViewCount());
        map.put("unlockAttempts", lock.getUnlockAttempts());
        map.put("maxAttempts", lock.getMaxAttempts());
        return map;
    }

    private Map<String, Object> convertToSummaryMap(FinalAnswerLock lock) {
        Map<String, Object> map = new HashMap<>();
        map.put("id", lock.getId());
        map.put("lockName", lock.getLockName());
        map.put("category", lock.getCategory());
        map.put("status", lock.getStatus());
        map.put("unlockDate", lock.getUnlockDate());
        map.put("createdAt", lock.getCreatedAt());
        return map;
    }

    private String convertLockToJson(FinalAnswerLock lock) {
        try {
            Map<String, Object> lockData = new HashMap<>();
            lockData.put("id", lock.getId());
            lockData.put("lockName", lock.getLockName());
            lockData.put("lockDescription", lock.getLockDescription());
            lockData.put("category", lock.getCategory());
            lockData.put("status", lock.getStatus());
            lockData.put("unlockDate", lock.getUnlockDate());
            lockData.put("createdAt", lock.getCreatedAt());
            lockData.put("contentType", lock.getContentType());
            lockData.put("textContent", lock.getTextContent());
            // 简单的JSON序列化
            return lockData.toString();
        } catch (Exception e) {
            return "{}";
        }
    }
}
